package models.base;

import facade.AppContext;
import facade.open.request.base.AdminMenuRequest;
import helper.GlobalConfig;
import models.common.BaseModel;
import models.constants.DeletedStatus;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import play.db.jpa.JPA;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Query;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static helper.BeanHelper.safeSetValue;

/**
 * created by weiwei on 2018/02/08
 * 菜单表，
 */


@Entity
@Table(name = "admin_menu_items", schema = GlobalConfig.MIGAO_DB_SCHEMA)
public class AdminMenu extends BaseModel {


    /**
     * 业务编号
     */
    @Column(name = "code")
    public String code;


    /**
     * 页面所在文件夹
     * 用于前台菜单  菜单名称
     */
    @Column(name = "name")
    public String name;
    /**
     * 菜单项名称
     */
    @Column(name = "title")
    public String title;


    @Column(name = "icon",length = 50)
    public String icon = "layui-icon-component";

    /**
     * 页面请求地址
     * 用于前台页面
     */
    @Column(name = "url",length = 255)
    public String url;

    /**
     * 父节点ID
     */
    @Column(name = "parent_id")
    public String parentId;

    /**
     * 排序号
     */
    @Column(name = "show_order")
    public Integer showOrder = 0;


    @Column(name = "remark")
    public String remark;


    public static AdminMenu findOne(String id){
        return AdminMenu.find("deleted = ? and id = ? " , DeletedStatus.UN_DELETED , id).first();
    }

    public static Boolean existByTitle(String title){
        if(StringUtils.isEmpty(title)) return null;
        return count("deleted = ? and title = ? " , DeletedStatus.UN_DELETED , title)>0;
    }

    /**
     * 查询所有菜单
     * @return
     */
    public static List<AdminMenu>  findAllMenu(String businessId) {
        if (StringUtils.isEmpty(businessId)) {
            return AdminMenu.find("deleted = ? order by showOrder,code asc", DeletedStatus.UN_DELETED).fetch();
        }else{

            String sqlSelect = "SELECT m.id,m.code,m.name,m.title,m.icon,m.url,m.parent_id as parentId,m.show_order as showOrder,m.remark,m.created_at as createdAt,bo.business_id as businessId from admin_menu_items m left join admin_business_operates bo on bo.menu_id = m.id and bo.business_id='"+businessId+"' where m.deleted=0 order by m.show_order,m.code asc";
            System.out.println(sqlSelect);
            Query query = JPA.em().createNativeQuery(sqlSelect);
            query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            return query.getResultList();
        }
    }
    /**
     * 根据父节点ID 查询
     * @param parentId
     * @return
     */
    public static List<AdminMenu>  findByParentId(String parentId){
        return AdminMenu.find("deleted = ? and parentId = ?" , DeletedStatus.UN_DELETED,parentId).fetch();
    }


    //与Role所拥有到权限联合查询 获取角色所有权限的关联菜单列表
    public static List<AdminMenu> findByRoleId(String roleId){
        List<AdminMenu> menuList = new ArrayList<>();
        if(!StringUtils.isEmpty(roleId)) {
            List<AdminRoleOperate> roleOperateList = AdminRoleOperate.findByRoleId(roleId);
            if (roleOperateList != null && roleOperateList.size() > 0) {
                for (AdminRoleOperate roleOperate : roleOperateList) {
                    if(roleOperate.business != null) {
                        List<AdminBusinessOperate> businessOperateList = AdminBusinessOperate.findByBusinessId(roleOperate.business.id);
                        if (businessOperateList != null && businessOperateList.size()>0) {
                            for (AdminBusinessOperate businessOperate : businessOperateList) {
                                if(!menuList.contains(businessOperate.menuItem)) {
                                    menuList.add(businessOperate.menuItem);
                                }
                            }
                        }
                    }
                }
            }
        }
        return menuList;
    }

    public static AdminMenu create(AdminMenuRequest request){
        AdminUser loginUser = AppContext.currentUser(); //获取登录用户

        AdminMenu menu = new AdminMenu();
        safeSetValue(request.name, value -> menu.name = value );
        safeSetValue(request.title, value -> menu.title = value );
        if(StringUtils.isEmpty(request.parentId)) request.parentId = "0";
        safeSetValue(request.parentId, value -> menu.parentId = value );
        if(StringUtils.isEmpty(request.icon)) request.icon = "layui-icon-component";
        safeSetValue(request.icon, value -> menu.icon = value );
        safeSetValue(request.url, value -> menu.url = value );
        if(request.showOrder == null) request.showOrder = 0;
        safeSetValue(request.showOrder, value -> menu.showOrder = value );
        safeSetValue(request.remark, value -> menu.remark = value );
        menu.code = getNewCode(request.parentId).toString();
        menu.save();

        return menu ;
    }

    public static AdminMenu update(AdminMenu menu, AdminMenuRequest request){
        AdminUser loginUser = AppContext.currentUser(); //获取登录用户

        safeSetValue(request.name, value -> menu.name = value );
        safeSetValue(request.title, value -> menu.title = value );
        safeSetValue(request.parentId, value -> menu.parentId = value );
        if(StringUtils.isEmpty(request.icon)) request.icon = "layui-icon-component";
        safeSetValue(request.icon, value -> menu.icon = value );
        safeSetValue(request.url, value -> menu.url = value );
        if(request.showOrder == null) request.showOrder = 0;
        safeSetValue(request.showOrder, value -> menu.showOrder = value );
        safeSetValue(request.remark, value -> menu.remark = value );

        menu.modifyAt = new Date() ;
        menu.modifyUser = loginUser ;
        menu.save();

        return menu ;
    }


    public static Integer getNewCode(String parentId) {
        Integer code = 1000;
        //查询最新记录code
        if ("0".equals(parentId)) {
            //根目录
            AdminMenu menu = AdminMenu.find("parentId = '0' order by createdAt desc").first();
            if(menu != null){
                code = Integer.valueOf(menu.code)+1000;
            }
        } else {
            //子目录
            AdminMenu menu = AdminMenu.find("parentId = ? order by createdAt desc", parentId).first();

            if (menu != null) {
                code = Integer.valueOf(menu.code) + 1;
            } else {
                menu = AdminMenu.findOne(parentId);
                if (menu != null) {
                    code = Integer.valueOf(menu.code) + 1;

                }

            }

        }


        return code;

    }

}
